package com.csx.framework.springboot.sample.data.transaction;

import com.csx.framework.springboot.sample.data.transaction.entity.User;
import com.csx.framework.springboot.sample.data.transaction.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.List;

/**
 * <p> what does this class do ? </p>
 * <p> How does it work ?</p>
 * <p> Why does it do this ?</p>
 *
 * @author cuisongxu
 * @date 2024/12/21 周六 13:02
 */
@Component
public class TransactionTemplateSample {

    @Autowired
    private TransactionTemplate transactionTemplate;

    @Autowired
    private UserService userService;

    /**
     * 使用 TransactionTemplate 进行事务操作
     */
    public void testTransactionTemplate() {
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus status) {
                try {
                    // 业务代码
                    userService.insertUser(999L, "李", "四", 18, "杭州");
                    // 模拟插入失败,触发回滚
                    userService.insertUserFail(1000L, "张2", "2", 18, "深圳");
                    List<User> allUsers = userService.getAllUsers();
                    System.out.println(allUsers);
                }catch (Exception e) {
                    // 回滚
                    status.setRollbackOnly();
                }
            }
        });
    }
}
